package com.nhatviet.webservice.helpers;

import java.util.List;

import com.nhatviet.webservice.R;
import com.nhatviet.webservice.models.FlickrPhoto;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListItemAdapter extends ArrayAdapter<FlickrPhoto>
{
	private final List<FlickrPhoto>	values;
	private final Activity			activity;

	/* Make higher performance */
	private static class ViewHolder
	{
		public TextView		textView;
		public ImageView	imageView;
	}

	public ListItemAdapter(Activity activity, List<FlickrPhoto> values)
	{
		super(activity, R.layout.flickr_item_in_list, values);
		this.values = values;
		this.activity = activity;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View rowView = convertView;
		final ViewHolder viewHolder;

		if (rowView == null)
		{
			LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			rowView = layoutInflater.inflate(R.layout.flickr_item_in_list, parent, false);
			viewHolder = new ViewHolder();
			viewHolder.textView = (TextView) rowView.findViewById(R.id.text_item);
			viewHolder.imageView = (ImageView) rowView.findViewById(R.id.image_view);
			rowView.setTag(viewHolder);
		}
		else
		{
			viewHolder = (ViewHolder) rowView.getTag();
		}
		/*Initiate items*/
		final FlickrPhoto currentPhoto = values.get(position);
		viewHolder.textView.setText(currentPhoto.getId());
		if (currentPhoto.getBitmap() != null)
		{
			viewHolder.imageView.setImageBitmap(currentPhoto.getBitmap());
		}
		else {
			viewHolder.imageView.setImageBitmap(null);
			new ImageLoadTask(activity, viewHolder.imageView, currentPhoto).execute(FlickrService.getURLPhoto(currentPhoto.getId(), currentPhoto.getServer(), currentPhoto.getFarm(), currentPhoto.getSecret(), FlickrService.SIZE_SUFFIX_SMALL_240));
		}
		/*Return view*/
		return rowView;
	}
}
